/*
 * Ryan Swartzman
 * Logan Freesh
 * 6/11/12
 * 
 */

package com.paad.todolist;

import java.util.ArrayList;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

public class ShoppinglistsActivity extends Activity {
	
  static final private int ADD_NEW_TODO = Menu.FIRST;
  static final private int REMOVE_TODO = Menu.FIRST + 1;
  
  private static final String TEXT_ENTRY_KEY = "TEXT_ENTRY_KEY";
  private static final String ADDING_ITEM_KEY = "ADDING_ITEM_KEY";
  private static final String SELECTED_INDEX_KEY = "SELECTED_INDEX_KEY";
  
  private boolean addingNew = false;
  private ArrayList<Army> Armies;
  private ListView myListView;
  private EditText myEditText;
  private ArmyAdapter aa;
  int armyId1 = -1, armyId2 = -1;
  

  ArmyDBAdapter armyDBAdapter;
  Cursor armyCursor;
  
  /** Called when the activity is first created. */
  public void onCreate(Bundle bundle) {
    super.onCreate(bundle);
    setContentView(R.layout.main);

    myListView = (ListView)findViewById(R.id.myListView);
    myEditText = (EditText)findViewById(R.id.myEditText);

    Armies = new ArrayList<Army>();
    int resID = R.layout.shoppinglist_entity;
    aa = new ArmyAdapter(this, resID, Armies);
    myListView.setAdapter(aa);
    final Button button1 = (Button)findViewById(R.id.button1);

    myEditText.setOnKeyListener(new OnKeyListener() {
      public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN)
          if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
            String newShoppinglistName = myEditText.getText().toString();
            Army toInsert = new Army(newShoppinglistName);
            toInsert.setId((int)armyDBAdapter.insertArmy(toInsert.getName()));
            //updateArray();
            populateArmyList();
            myEditText.setText("");
            aa.notifyDataSetChanged();
            cancelAdd();
            return true;
          }
        return false;
      }
    });
    
    button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
        	/*Army army1 = new Army();
        	Army army2 = new Army();
        	army1.setId(Armies.get(armyId1).getId());
        	army2.setId(Armies.get(armyId2).getId());
        	
        	Cursor itemIdCursor = armyDBAdapter.getArmyCursor(army1.getId());
            startManagingCursor(itemIdCursor);
            itemIdCursor.requery();
            Cursor itemCursor;
            if (itemIdCursor.moveToFirst())
        	    do {
        	    	int item_id = itemIdCursor.getInt(itemIdCursor.getColumnIndex(ArmyDBAdapter.KEY_LISTING_SQUAD_ID));
        	    	itemCursor = armyDBAdapter.getSquadCursor(item_id);
        	    	if(itemCursor.moveToFirst())
        	    	{
        		      String name = itemCursor.getString(itemCursor.getColumnIndex(ArmyDBAdapter.KEY_SQUAD_TYPE));
        		      //Boolean is_done = itemsCursor.getInt(itemsCursor.getColumnIndex(ShoppinglistsDBAdapter.KEY_ITEM_DONE)) > 0;
        		      int id = itemCursor.getInt(itemCursor.getColumnIndex(ArmyDBAdapter.KEY_ID));
        		      Squad newItem = new Squad(name);
        		      newItem.setId(id);
        		      newItem.setName(name);
        		      if(army1.pointsUsed < army1.squadPoints && army1.pointsUsed + newItem.squadPoints <= army1.squadPoints){
        		    	  army1.addSquad(newItem);
        		    	  army1.pointsUsed += newItem.squadPoints;
        		      }
        		      itemCursor.close();
        	    	}
        	    } while(itemIdCursor.moveToNext());
        	
            itemIdCursor = armyDBAdapter.getArmyCursor(army2.getId());
            startManagingCursor(itemIdCursor);
            itemIdCursor.requery();
            if (itemIdCursor.moveToFirst())
        	    do {
        	    	int item_id = itemIdCursor.getInt(itemIdCursor.getColumnIndex(ArmyDBAdapter.KEY_LISTING_SQUAD_ID));
        	    	itemCursor = armyDBAdapter.getSquadCursor(item_id);
        	    	if(itemCursor.moveToFirst())
        	    	{
        		      String name = itemCursor.getString(itemCursor.getColumnIndex(ArmyDBAdapter.KEY_SQUAD_TYPE));
        		      //Boolean is_done = itemsCursor.getInt(itemsCursor.getColumnIndex(ShoppinglistsDBAdapter.KEY_ITEM_DONE)) > 0;
        		      int id = itemCursor.getInt(itemCursor.getColumnIndex(ArmyDBAdapter.KEY_ID));
        		      Squad newItem = new Squad(name);
        		      newItem.setId(id);
        		      newItem.setName(name);
        		      if(army2.pointsUsed < army2.squadPoints && army2.pointsUsed + newItem.squadPoints <= army2.squadPoints){
        		    	  army2.addSquad(newItem);
        		    	  army2.pointsUsed += newItem.squadPoints;
        		      }
        		      itemCursor.close();
        	    	}
        	    } while(itemIdCursor.moveToNext());*/
        	
        	if(armyId1 == -1 || armyId2 == -1)
        	{
        		Toast toast = Toast.makeText(getBaseContext(), "Use the options menu to create armies, and the context menu (long click) to select two of them.",
						Toast.LENGTH_LONG);
				toast.show();
        	}
        	
        	Intent intent = new Intent(getApplicationContext(), BattlegridActivity.class);
        	intent.putExtra("army1", armyId1);
        	intent.putExtra("army2", armyId2);
        	//intent.putExtra("id", item.id);
        	startActivity(intent);
        	
        }
    });
        
    myListView.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> av, View v, int position, long id) {
    	Army item = Armies.get(position);
    	Intent intent = new Intent(getApplicationContext(), ViewShoppinglistActivity.class);
    	intent.putExtra("id", item.id);
    	startActivity(intent);
      }
    });

    registerForContextMenu(myListView);
    restoreUIState();

    armyDBAdapter = new ArmyDBAdapter(this);


    // Open or create the database
    armyDBAdapter.open();
    
    //shoppinglistDBAdapter.dropTable();

    populateArmyList();
  }
  
  private void populateArmyList() {
    // Get all the shoppinglists from the database.
    armyCursor = armyDBAdapter.getAllArmyCursor();
    startManagingCursor(armyCursor);
      
    // Update the array.
    updateArray();
  }

  private void updateArray() {
	  armyCursor.requery();

	  Armies.clear();
	    
	  if (armyCursor.moveToFirst())
	    do { 
	      Integer id = armyCursor.getInt(armyCursor.getColumnIndex(ArmyDBAdapter.KEY_ID));
	      String task = armyCursor.getString(armyCursor.getColumnIndex(ArmyDBAdapter.KEY_ARMY_NAME));

	      Army newItem = new Army(task);
	      newItem.setId(id);
	      Armies.add(Armies.size(), newItem);
	    } while(armyCursor.moveToNext());
	  
	  aa.notifyDataSetChanged();
	}

  private void restoreUIState() {
    // Get the activity preferences object.
    SharedPreferences settings = getPreferences(0);

    // Read the UI state values, specifying default values.
    String text = settings.getString(TEXT_ENTRY_KEY, "");
    Boolean adding = settings.getBoolean(ADDING_ITEM_KEY, false);

    // Restore the UI to the previous state.
    if (adding) {
      addNewItem();
      myEditText.setText(text);
    }
  }
  
  @Override
  public void onSaveInstanceState(Bundle outState) {
    outState.putInt(SELECTED_INDEX_KEY, myListView.getSelectedItemPosition());

    super.onSaveInstanceState(outState);
  }

  @Override
  public void onRestoreInstanceState(Bundle savedInstanceState) {
    int pos = -1;

    if (savedInstanceState != null)
      if (savedInstanceState.containsKey(SELECTED_INDEX_KEY))
        pos = savedInstanceState.getInt(SELECTED_INDEX_KEY, -1);

    myListView.setSelection(pos);
  }
  
  @Override
  protected void onPause() {
    super.onPause();
    
    // Get the activity preferences object.
    SharedPreferences uiState = getPreferences(0);
    // Get the preferences editor.
    SharedPreferences.Editor editor = uiState.edit();

    // Add the UI state preference values.
    editor.putString(TEXT_ENTRY_KEY, myEditText.getText().toString());
    editor.putBoolean(ADDING_ITEM_KEY, addingNew);
    // Commit the preferences.
    editor.commit();
    
    // Closes the DB connection.
    armyDBAdapter.close();
  }
  
  @Override
  public void onResume() {
	super.onResume();
	  	
	// Reopens the DB connection.
	armyDBAdapter.open();
  }
  
  
  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);

    // Create and add new menu items.
    MenuItem itemAdd = menu.add(0, ADD_NEW_TODO, Menu.NONE,
                                R.string.add_new);
    MenuItem itemRem = menu.add(0, REMOVE_TODO, Menu.NONE,
                                R.string.remove);

    // Assign icons
    itemAdd.setIcon(R.drawable.add_new_item);
    itemRem.setIcon(R.drawable.remove_item);

    // Allocate shortcuts to each of them.
    itemAdd.setShortcut('0', 'a');
    itemRem.setShortcut('1', 'r');

    return true;
  }

  @Override
  public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);

    int idx = myListView.getSelectedItemPosition();

    String removeTitle = getString(addingNew ? 
                                   R.string.cancel : R.string.remove);

    MenuItem removeItem = menu.findItem(REMOVE_TODO);
    removeItem.setTitle(removeTitle);
    removeItem.setVisible(addingNew || idx > -1);

    return true;
  }
  
  @Override
  public void onCreateContextMenu(ContextMenu menu, 
                                  View v, 
                                  ContextMenu.ContextMenuInfo menuInfo) {
    super.onCreateContextMenu(menu, v, menuInfo);

    menu.setHeaderTitle("Selected Army");
    menu.add(0, REMOVE_TODO, Menu.NONE, R.string.remove);
    menu.add(0, 3, Menu.NONE, "Set as Army 1");
    menu.add(0, 4, Menu.NONE, "Set as Army 2");
  }
  
  @Override
  public boolean onOptionsItemSelected(MenuItem item) {
    super.onOptionsItemSelected(item);

    int index = myListView.getSelectedItemPosition();

    switch (item.getItemId()) {
      case (REMOVE_TODO): {
        if (addingNew) {
          cancelAdd();
        } 
        else {
          removeItem(index);
        }
        return true;
      }
      case (ADD_NEW_TODO): { 
        addNewItem();
        return true; 
      }
      
    }

    return false;
  }
  
  @Override
  public boolean onContextItemSelected(MenuItem item) {  
    super.onContextItemSelected(item);
    AdapterView.AdapterContextMenuInfo menuInfo;
    menuInfo =(AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
    int index = menuInfo.position;
    int theId = (Armies.get(index)).getId();
    switch (item.getItemId()) {
      case (REMOVE_TODO): {
        removeItem(theId);
        return true;
      }
      case (3): { 
          armyId1 = theId;
          return true; 
        }
      case (4): { 
          armyId2 = theId;
          return true; 
        }
    }
    return false;
  }
  
  @Override
  public void onDestroy() {
    super.onDestroy();
      
    // Close the database
    armyDBAdapter.close();
  }
  
  private void cancelAdd() {
    addingNew = false;
    myEditText.setVisibility(View.GONE);
  }

  private void addNewItem() {
    addingNew = true;
    myEditText.setVisibility(View.VISIBLE);
    myEditText.requestFocus(); 
  }

  private void removeItem(int _index) {
    // Items are added to the listview in reverse order, so invert the index.
    armyDBAdapter.removeArmy(_index);
    updateArray();
  }
}